import jwt
from django.contrib.auth.models import AnonymousUser
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.permissions import BasePermission

from common.models import User
from fangtx.settings import SECRET_KEY


class CustomAuthorization(BasePermission):

    def has_permission(self, request, view):
        if not request.user or isinstance(request.user, AnonymousUser):
            return True
        for role in request.user.roles.all():
            for priv in role.privs.all():
                if priv.method == request.method and \
                        priv.url == request.path:
                    return True
        return False


class AllowGetAuthentication(BaseAuthentication):

    def authenticate(self, request):
        if request.method == 'GET':
            return None, None


class AllowPostAuthentication(BaseAuthentication):

    def authenticate(self, request):
        if request.method == 'POST':
            return None, None


class CustomAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.META.get('HTTP_TOKEN')
        if token:
            try:
                result = jwt.decode(token, SECRET_KEY, algorithm='HS256')
                user = User.objects.get(userid=result['data']['userid'])
                return user, token
            except Exception:
                pass
        raise AuthenticationFailed('请提供有效的身份认证标识')
